const qiniuUploader = require("./util/qiniuUploader");
export default {

	data: {
		pageData: {},
		'apiHost': 'https://www.bestsmartbee.com/',
		// 'apiHost': 'http://www.tenement.com:81/',
		'qiniuUrl': 'http://oi7jj3s01.bkt.clouddn.com/',
		debug: 1,
		wxapp: "",
		store_id: 1,
		// #ifdef MP-WEIXIN
		appid: 'wx9f625a953cb94652',
		app_type: 'wx',
		// #endif

		// #ifdef MP-ALIPAY
		appid: '2019081366241143',
		app_type: 'alipay',
		// #endif
		socketOpen: false,
		socketMsgQueue: [],
		socketRevQueue: {},
		getUserInfoCb: [],
		userFields: "user_id,store_id,phone,nickname,phone,avatarUrl,last_update_time",
		loginUrl: 'https://login.bestsmartbee.com/',
	},
	//上传图片
	upload: function(filePath, suc) {
		var that = this;
		// uni.showToast({
		//   title: '上传中...',
		//   icon: 'loading',
		//   duration: 5000
		// });
		qiniuUploader.upload(filePath, (res) => {
			uni.hideToast();
			suc ? suc(res) : '';
		}, (error) => {
			uni.hideToast();
			console.log('error: ' + error);
			that.alert(JSON.stringify(error));
		}, {
			region: 'ECN', // 华东区
			uploadURL: 'https://up.qiniup.com',
			domain: this.data.qiniuUrl,
			key: ((new Date().getTime()) + Math.random()) * 10000,
			uptokenURL: this.data.apiHost + '/api/upload/uptoken',
		})

	},

	runGetUserInfoCb: function(userInfo) {
		for (var i in this.data.getUserInfoCb) {
			var fun = this.data.getUserInfoCb[i];
			typeof fun == "function" && fun(userInfo);
		}
		this.data.getUserInfoCb = [];
	},

	loginByUserInfo: function(userInfo, cb) {
		// console.log(userInfo);
		var that = this;
		//调用登录接口
		uni.login({
			fail: function(res) {
				console.log(res);
			},
			success: function(loginRes) {
				// console.log("loginRes", loginRes);
				var pid = uni.getStorageSync("pid");
				if (pid > 0) {
					userInfo.pid = pid;
					uni.removeStorageSync("pid");
				}
				userInfo.method = "POST";
				userInfo.code = loginRes.code;
				userInfo.wxapp = that.data.wxapp;
				userInfo.fields = that.data.userFields;
				userInfo.rawData = JSON.stringify(userInfo.userInfo);
				var loginUrl;
				// #ifdef MP-WEIXIN
				loginUrl = "/api/user/loginByWxApp";
				// #endif
				// #ifdef MP-ALIPAY
				loginUrl = "/api/user/loginByAilpayApp";
				// #endif

				that.api(loginUrl, userInfo, function(userRes) {
					// if (userRes.code == 3 || !userRes.data.phone) {
					// 	that.bindPhone();
					// 	return false;
					// }
					if (userRes.code != 200 && userRes.code != 3) {
						that.alert(userRes.msg);
						return false;
					}
					// console.log(userRes);
					that.globalData.userInfo = userRes.data
					that.runGetUserInfoCb(that.globalData.userInfo);
					typeof cb == "function" ? cb(userRes) : '';
				});
			}
		})
	},
	globalData: {

	},
	wxGetUserInfo: function(cb) {
		var that = this;
		uni.getSetting({
			complete: function(res) {
				if (res.errMsg != "getSetting:ok") {
					that.alert(res.errMsg);
				}
				console.log("getSetting complete", res);
			},
			success: function(res) {
				console.log("getSetting success");
				console.log(res);
				console.log(res.authSetting['scope.userInfo']);
				if (res.authSetting['scope.userInfo']) {
					// 已经授权，可以直接调用 getUserInfo 获取头像昵称
					uni.getUserInfo({
						success: function(res) {
							that.loginByUserInfo(res);
						},
						fail: function(res) {
							that.alert('授权失败!');
						},
						complete: function(res) {
							console.log("getUserInfo complete", res);
						}
					})

				} else if (!res.authSetting['scope.userInfo']) {
					uni.reLaunch({
						url: '/pages/user/bindphone?page=auth',
						complete: function(res) {
							console.log(res);
						}
					})
				}
			}
		})
	},

	bindPhone: function() {
		uni.reLaunch({
			url: '/pages/user/bindphone?page=bindphone',
			complete: function(res) {
				console.log(res);
			}
		})
	},

	aliGetUserInfo: function(cb) {
		uni.reLaunch({
			url: '/pages/user/bindphone?page=auth',
			complete: function(res) {
				console.log(res);
			}
		})

	},

	getUserInfo: function(cb) {

		var that = this
		this.data.getUserInfoCb.push(cb);
		var user_info = uni.getStorageSync("user_info");
		if (user_info) {
			this.runGetUserInfoCb(user_info);
			//typeof cb == "function" && cb(this.globalData.userInfo)
		} else {
			if (this.data.getUserInfoCb.length > 1) {
				return;
			}
			// #ifdef MP-WEIXIN
			that.wxGetUserInfo();
			// #endif
			// #ifdef MP-ALIPAY
			that.aliGetUserInfo();
			// #endif
			// #ifdef H5
			that.H5GetUserInfo();
			// #endif
		}
	},

	H5GetUserInfo: function(callblack, fields) {
		var backUrl = window.location.href;
		var Request = this.GetRequest(backUrl);
		if (Request && Request.token) {
			this.loginByToken(Request.token, fields, callblack);
		} else {
			this.auth();
		}
	},
	loginByToken: function(token, fields, callblack) {
		var that = this;
		var userInfoUrl = that.data.loginUrl + "index/getUserInfoByToken/";

		this.api(userInfoUrl, {
			fields: that.data.userFields,
			token: token,
		}, function(data) {
			if (data.code > 0) {
				that.alert(data.msg);
				that.relogin();
			} else {
				uni.setStorageSync("user_info", data.userInfo);
				typeof(callblack) == "function" ? callblack(data.userInfo): "";
				// if (that.data.bindPhone && !data.userInfo.phone) {
				// 	that.bindPhone();
				// }
			}
		})
	},
	relogin: function(text) {
		var content = text ? text : '授权登录发现异常，是否重新登录？';
		var that = this;
		this.alert(content, function() {
			that.auth();
		});
	},

	auth: function() {
		var that = this;
		var backUrl = window.location.href;
		var search = that.GetRequest(window.location.search);
		var store_id = search.store_id ? search.store_id : 0;
		var scene_id = search.scene_id ? search.scene_id : 0;
		var loginUrl;
		if (that.isWeiXin()) {
			loginUrl = that.data.loginUrl + "index/getopenid/?backUrl=" + window.escape(backUrl);
		} else if (that.isAlipay()) {
			loginUrl = that.data.loginUrl + "index/loginH5ByAlipay/?act=getUserId&backUrl=" + window.escape(backUrl);
		} else {
			loginUrl = that.data.loginUrl + "index/synclogin/?backUrl=" + window.escape(backUrl);
		}
		if (store_id != 0) {
			loginUrl += "&store_id=" + store_id;
		} else if (scene_id != 0) {
			loginUrl += "&scene_id=" + scene_id;
		}
		window.location.href = loginUrl;
	},

	GetRequest: function(url) {
		var theRequest = new Object();
		if (url.indexOf("?") != -1) {
			var str = url.split("?");
			str = str[1];
			var strs = str.split("&");
			for (var i = 0; i < strs.length; i++) {
				var v = strs[i].split("=")[1];
				theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
			}
		}
		return theRequest;
	},

	isWeiXin: function() {
		//window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
		var ua = window.navigator.userAgent.toLowerCase();
		//通过正则表达式匹配ua中是否含有MicroMessenger字符串
		if (ua.match(/MicroMessenger/i) == 'micromessenger') {
			return true;
		} else {
			return false;
		}
	},
	isAlipay: function() {
		//window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
		var ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/Alipay/i) == "alipay") {
			return true;
		} else {
			return false;
		}
	},

	getUrl: function(url, data) {
		var params = this.requestParam(url, data);
		var json = params.param;
		var arg = Object.keys(json).map(function(key) {
			return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
		}).join("&");
		var hash = "wechat_redirect";

		if (params.url.indexOf("#") > -1) {
			var urls = params.url.split("#");
			url = urls[0];
			hash = urls[1];
		} else {
			url = params.url;
		}

		if (url.indexOf("?") > -1) {
			url = url + "&" + arg;
		} else {
			url = url + "?" + arg;
		}
		return url + "#" + hash;


	},
	//请求接口
	requestParam: function(url, data, cb) {
		var extJson = {};
		// #ifdef MP-ALIPAY
		extJson = my.getExtConfigSync();
		// #endif

		// #ifndef MP-ALIPAY
		// var extJson = uni.getExtConfigSync();
		if (uni.getExtConfigSync) {
			extJson = uni.getExtConfigSync();
		}
		// #endif


		console.log("extJson:", extJson);

		if (extJson && extJson.store_id) {
			this.data.store_id = extJson.store_id;
			this.data.appid = extJson.appid;
		}

		var host = this.data.apiHost;
		if (url.indexOf("http") !== 0) {
			url = host + url;
		}
		var param = {};
		var cbf = cb;
		if (typeof(data) == 'function') {
			cbf = data;
		} else if (typeof(data) == 'object') {
			param = data;
		}
		this.data.debug == 1 ? param['time'] = Date.parse(new Date()) : '';
		if (!param['store_id']) {
			param['store_id'] = this.data.store_id;
		}
		if (param['store_id']==-1) {
			delete param['store_id'];
		}
		param['appid'] = this.data.appid;

		var user_info =  uni.getStorageSync("user_info");
		if (!param['token']) {
			param['token'] = user_info ? user_info.token : '';
		}
		// #ifdef MP-WEIXIN
		param['from_wx_app'] = 1;
		// #endif
		// #ifdef MP-ALIPAY
		param['from_alipay_app'] = 1;
		// #endif
		param['runThreadKey'] = 'eee50acd6ee441d75ad2b87c9747d09b';
		console.log("param:", param);
		return {
			'param': param,
			'url': url,
			'cb': cbf,
		};
	},



	api: function(url, data = {}, cb) {
		if (url.indexOf("http") === 0) {
			var apiUrl = url;
		} else {
			var apiUrl = this.data.apiHost + url;
		}

		this.postData(apiUrl, data, cb);
	},

	postData: function(url, data, cb) {
		//  uni.showToast({
		//    title: '加载中...',
		//    icon: 'loading',
		//    duration: 5000
		//  });
		uni.showNavigationBarLoading();
		var p = this.requestParam(url, data, cb);
		console.log("postData:", p);
		var method = p['param']['method'] ? p['param']['method'] : 'GET';
		// console.log("postData:");

		var cbf = p['cb'];
		uni.request({
			url: p['url'], //仅为示例，并非真实的接口地址
			data: p['param'],
			method: method,
			// header: {
			//    'Content-Type': 'application/json'
			// },
			header: {
				"Content-Type": "application/x-www-form-urlencoded"
			},
			success: function(res) {
				typeof(cbf) == "function" ? cbf(res.data): "";
				// uni.hideToast();
				uni.hideNavigationBarLoading();
			}
		})
	},
	//页面的数据 
	//页面的数据 
	setPageData: function(pageName, data = {}) {
		var curData = this.data.pageData[pageName] ? this.data.pageData[pageName] : {};

		for (var i in data) {
			//console.log("i", i, data[i]);
			curData[i] = data[i];
		}

		this.data.pageData[pageName] = curData;

	},
	getPageData: function(pageName, key = '') {
		var curData = this.data.pageData[pageName];
		if (key) {
			return curData ? curData[key] : null;
		} else {
			return curData;
		}
	},
	pay: function(order_sn, suc, fail) {
		// #ifdef MP-WEIXIN
		var paytype = "pay.weixin.jspay";
		var provider = "wxpay";
		// #endif
		// #ifdef MP-ALIPAY
		var paytype = "pay.alipay.jspay";
		var provider = "alipay";
		// #endif

		//  if($("#payBoxHide").length==0){
		// 	$("body").append('<div style="display:none" id="payBoxHide"></div>');
		//  }
		//  $("#payBoxHide").load(payurl,function(){                    
		//    app.hideLoad();
		// });			
		var that = this;
		this.api("/apiv2/pay/run", {
			order_sn: order_sn,
			paytype: paytype,
			getJson: 1
		}, function(res) {
			if (res.code != 200) {
				that.alert(res.msg);
				return;
			}
			if (provider == "wxpay") {
				var PayInfo = JSON.parse(res.data.PayInfo);
				PayInfo.success = function(res) {
					suc ? suc(res) : '';
				};
				PayInfo.fail = function(res) {
					that.alert(JSON.stringify(res));
					fail ? fail(res) : '';
				};
				wx.requestPayment(PayInfo);
			} else if (provider == "alipay") {
				var tradeNO = res.data.PrePayId ? res.data.PrePayId : res.data.trade_no;
				my.tradePay({
					tradeNO: tradeNO, // 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号trade_no
					success: (res) => {
						if (res.resultCode == "9000") {
							suc ? suc(res) : '';
						} else if (res.resultCode != "6001") {
							that.alert(JSON.stringify(res));
						} else {
							fail ? fail(res) : '';
						}
					},
					fail: (res) => {
						that.alert(JSON.stringify(res));
						fail ? fail(res) : '';
					}
				});
			}
		})

	},
	randomNum: function(minNum, maxNum) {
		switch (arguments.length) {
			case 1:
				return parseInt(Math.random() * minNum + 1, 10);
				break;
			case 2:
				return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
				//或者 Math.floor(Math.random()*( maxNum - minNum + 1 ) + minNum );
				break;
			default:
				return 0;
				break;
		}
	},
	alert: function(str, cb) {
		uni.showModal({
			title: '提示',
			content: str,
			showCancel: false,
			success: function(res) {
				if (res.confirm) {
					cb ? cb() : '';
				}
			}
		});
	}
}
